package com.example.web_little_work.Controller;

import com.example.web_little_work.BookRepository;
import com.example.web_little_work.Entity.Book;
import com.example.web_little_work.Entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Controller
public class BookController {
    @Autowired
    private BookRepository bookRepository;
    private boolean isLogin = false;

    @RequestMapping("show")
    public ModelAndView show() {
        List<Book> resultList = bookRepository.findAll();
        if (!isLogin) {
            ModelAndView login = new ModelAndView("Login");
            return login;
        }
        ModelAndView mv = new ModelAndView("BookShow");
        mv.addObject("bookList", resultList);
//        mv.addObject("bookList", returnBookList);
        return mv;
    }

    @RequestMapping("showAdd")
    public ModelAndView showAdd() {
        if (!isLogin) {
            ModelAndView login = new ModelAndView("Login");
            return login;
        }
        ModelAndView mv = new ModelAndView("BookAdd");
        return mv;
    }

    @RequestMapping("add")
    public String add(Book book) {
        bookRepository.save(book);
        return "redirect:show";
    }

    @RequestMapping("showDelete")
    public ModelAndView showDelete() {
        if (!isLogin) {
            ModelAndView login = new ModelAndView("Login");
            return login;
        }
        ModelAndView mv = new ModelAndView("Delete");
        return mv;
    }

    @RequestMapping("delete")
    public String delete(long bookId) {
        bookRepository.deleteById(bookId);
        return "redirect:show";
    }

    @RequestMapping("showLogin")
    public ModelAndView showLogin() {
        ModelAndView mv = new ModelAndView("Login");
        return mv;
    }

    @RequestMapping("login")
    public String login(User user) {
        if (user.getUserName().equals("yhn") && user.getUserPassword().equals("123456")) {
            this.isLogin = true;
            return "redirect:show";
        }
        return "redirect:login";
    }
}
